package xin.clips.web.controller.system;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import xin.clips.common.annotation.VisistLog;
import xin.clips.common.config.ClipsConfig;
import xin.clips.common.constant.ShiroConstants;
import xin.clips.common.core.controller.BaseController;
import xin.clips.common.core.domain.AjaxResult;
import xin.clips.common.core.domain.entity.SysDept;
import xin.clips.common.core.domain.entity.SysDictData;
import xin.clips.common.core.domain.entity.SysMenu;
import xin.clips.common.core.domain.entity.SysUser;
import xin.clips.common.core.page.TableDataInfo;
import xin.clips.common.core.text.Convert;
import xin.clips.common.enums.gy.DeviceStatusEnum;
import xin.clips.common.enums.gy.InnerMessageStatusEnum;
import xin.clips.common.enums.gy.WorkOrderStatusEnum;
import xin.clips.common.utils.*;
import xin.clips.framework.shiro.service.SysPasswordService;
import xin.clips.system.domain.SysNotice;
import xin.clips.system.domain.gy.*;
import xin.clips.system.dto.NameValueDataDTO;
import xin.clips.system.dto.GyDeviceStatusDataDTO;
import xin.clips.system.service.*;
import xin.clips.system.service.gy.*;

/**
 * 首页 业务处理
 *
 * @author clips
 */
@Controller
public class SysIndexController extends BaseController {
    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private IGyDeviceService deviceService;

    @Autowired
    private IGyDeviceAlarmRecordService gyDeviceAlarmRecordService;

    @Autowired
    private IGyDeviceEarlywarnRecordService earlywarnRecordService;

    @Autowired
    private ISysNoticeService noticeService;

    @Autowired
    private IGyInnerMessageService innerMessageService;

    @Autowired
    private IGyWorkOrderService workOrderService;


    //    @GetMapping("/")
//    public String login(ModelMap mmap)
//    {
//
//        return "login";
//    }
    // 系统首页
    @GetMapping("/index")
    public String index(ModelMap mmap) {

        // 取身份信息
        SysUser user = getSysUser();
        // 根据用户id取出菜单
        List<SysMenu> menus = menuService.selectMenusByUser(user);
        mmap.put("menus", menus);
        mmap.put("user", user);
        mmap.put("sideTheme", configService.selectConfigByKey("sys.index.sideTheme"));
        mmap.put("skinName", configService.selectConfigByKey("sys.index.skinName"));
        Boolean footer = Convert.toBool(configService.selectConfigByKey("sys.index.footer"), true);
        Boolean tagsView = Convert.toBool(configService.selectConfigByKey("sys.index.tagsView"), true);
        mmap.put("footer", footer);
        mmap.put("tagsView", tagsView);
        mmap.put("mainClass", contentMainClass(footer, tagsView));
        mmap.put("copyrightYear", ClipsConfig.getCopyrightYear());
        mmap.put("demoEnabled", ClipsConfig.isDemoEnabled());
        mmap.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
        mmap.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));
        mmap.put("isMobile", ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")));
        SysDept sysDept = sysDeptService.selectDeptById(user.getDeptId());
        if (StringUtils.isNotNull(sysDept)) {
            mmap.put("sysDept", sysDept);
        }
        // 菜单导航显示风格
        String menuStyle = configService.selectConfigByKey("sys.index.menuStyle");
        // 移动端，默认使左侧导航菜单，否则取默认配置
        String indexStyle = ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")) ? "index" : menuStyle;

        // 优先Cookie配置导航菜单
        Cookie[] cookies = ServletUtils.getRequest().getCookies();
        for (Cookie cookie : cookies) {
            if (StringUtils.isNotEmpty(cookie.getName()) && "nav-style".equalsIgnoreCase(cookie.getName())) {
                indexStyle = cookie.getValue();
                break;
            }
        }
        String webIndex = "topnav".equalsIgnoreCase(indexStyle) ? "index-topnav" : "index";

        //获取用户关联的站内信未读消息
        GyInnerMessage msg = new GyInnerMessage();
        msg.setAcceptUserId(ShiroUtils.getUserId());
        Integer msgTotal = innerMessageService.selectUnreadInnerMessageTotalByUserId(msg);
        mmap.put("msgTotal", msgTotal);
        return webIndex;
    }

    // 锁定屏幕
    @GetMapping("/lockscreen")
    public String lockscreen(ModelMap mmap) {
        mmap.put("user", getSysUser());
        ServletUtils.getSession().setAttribute(ShiroConstants.LOCK_SCREEN, true);
        return "lock";
    }

    /**
     * 查询设备预警记录列表
     */
    @PostMapping("/system/deviceEarlyWaningRecordlistLimt")
    @ResponseBody
    public TableDataInfo deviceEarlyWaningRecordlistLimt() {
        //startPage();
        GyDeviceEarlywarnRecord deviceEarlywarnRecord=    new GyDeviceEarlywarnRecord();
//        if(!ShiroUtils.getLoginName().equals("admin")){
//            SysUser sysUser = userService.selectUserById(ShiroUtils.getUserId());
//            String locationId = sysUser.getLocationId();
//            if(StringUtils.isNotEmpty(locationId)){
//                deviceEarlywarnRecord.setLocationId(Integer.parseInt(locationId));
//            }
//        }
        List<GyDeviceEarlywarnRecord> list = earlywarnRecordService.selectGyDeviceEarlywarnRecordListLimit(deviceEarlywarnRecord);
        return getDataTable(list);
    }

    /**
     * 查询设备告警记录列表
     */
    @PostMapping("/system/deviceAlarmRecordlistLimit")
    @ResponseBody
    public TableDataInfo deviceAlarmRecordlistLimit( ) {
        GyDeviceAlarmRecord deviceAlarmRecord=    new GyDeviceAlarmRecord();
//        if(!ShiroUtils.getLoginName().equals("admin")){
//            SysUser sysUser = userService.selectUserById(ShiroUtils.getUserId());
//            String locationId = sysUser.getLocationId();
//            if(StringUtils.isNotEmpty(locationId)){
//                deviceAlarmRecord.setLocationId(Integer.parseInt(locationId));
//            }
//        }
        List<GyDeviceAlarmRecord> list = gyDeviceAlarmRecordService.selectGyDeviceAlarmRecordListLimit(deviceAlarmRecord);
        return getDataTable(list);
    }

    // 解锁屏幕
    @PostMapping("/unlockscreen")
    @ResponseBody
    public AjaxResult unlockscreen(String password) {
        SysUser user = getSysUser();
        if (StringUtils.isNull(user)) {
            return AjaxResult.error("服务器超时，请重新登录");
        }
        if (passwordService.matches(user, password)) {
            ServletUtils.getSession().removeAttribute(ShiroConstants.LOCK_SCREEN);
            return AjaxResult.success();
        }
        return AjaxResult.error("密码不正确，请重新输入。");
    }

    // 切换主题
    @GetMapping("/system/switchSkin")
    public String switchSkin() {
        return "skin";
    }

    // 切换菜单
    @GetMapping("/system/menuStyle/{style}")
    public void menuStyle(@PathVariable String style, HttpServletResponse response) {
        CookieUtils.setCookie(response, "nav-style", style);
    }

    // 系统介绍
    @GetMapping("/system/main")
    public String main(ModelMap mmap) {
        mmap.put("loginName", ShiroUtils.getLoginName());
        mmap.put("notices", noticeService.selectMainNoticeList(new SysNotice()));
        mmap.put("version", ClipsConfig.getVersion());
        GyInnerMessage msg = new GyInnerMessage();
        if (!ShiroUtils.getLoginName().equals("admin")) {
            msg.setAcceptUserId(ShiroUtils.getUserId());
        }
        msg.setInnerMessageStatus(Integer.parseInt(InnerMessageStatusEnum.UNREAD.getCode()));
        List<GyInnerMessage> msgList = innerMessageService.selectGyInnerMessageListLimt(msg);
        mmap.put("msgList", msgList);
        mmap.put("waitWork",msgList.size());
        Long userId = ShiroUtils.getUserId(); // 获取用户id
        SysUser sysUser = userService.selectUserById(userId);
        String locationId = sysUser.getLocationId();
        //String str = DictUtils.getDictLabel("gy_device_type", "机械臂");
        SysDictData typeDictData = new SysDictData();
        typeDictData.setDictType("gy_device_type");      //设备类型
        List<SysDictData> typeDicts = dictDataService.selectDictDataList(typeDictData);
        List<NameValueDataDTO> deviceTypeDTOS = new ArrayList<>();
        int alarmTotal = 0; //告警数量
        int offlineTotal =0; //离线数量
        int earlyWarnTotal=0 ; //预警数量
        int deviceTotal =0; //设备总数
        int waitWork=0; //待办工单数
        for (SysDictData typeData : typeDicts) {
            NameValueDataDTO gyDeviceTypeDTO = new NameValueDataDTO(typeData.getDictLabel(), "0");
            deviceTypeDTOS.add(gyDeviceTypeDTO);
        }
        GyDevice gyDevice = new GyDevice();
//        if (StringUtils.isNotEmpty(locationId)) {
//            gyDevice.setLocationId(Integer.parseInt(locationId));//根据用户所在的学院统计
//        }
        List<GyDevice> list = deviceService.selectGyDeviceByDeviceType(gyDevice);

        for (NameValueDataDTO count : deviceTypeDTOS) {
            for (GyDevice device : list) {
                if (device.getDeviceType().toString()
                        .equals(DictUtils.getDictValue("gy_device_type", count.getName()))) {
                    count.setValue(device.getCount().toString());
                    deviceTotal+=device.getCount();
                }
            }
        }

        mmap.put("list", deviceTypeDTOS.toArray());
        mmap.put("deviceTotal", deviceTotal);

        SysDictData statusDictData = new SysDictData();
        statusDictData.setDictType("gy_device_status");  //设备状态
        List<SysDictData> statusDicts = dictDataService.selectDictDataList(statusDictData);


        List<String> typeList = new ArrayList<>();
        for (SysDictData typeData : typeDicts) {
            typeList.add(typeData.getDictLabel());
        }


        List<String> statusList = new ArrayList<>();
        List<GyDeviceStatusDataDTO> gyDeviceStatusDatumDTOS = new ArrayList<>();
        for (SysDictData statusData : statusDicts) {
            statusList.add(statusData.getDictLabel());
            GyDeviceStatusDataDTO gyDeviceStatusDataDTO = new GyDeviceStatusDataDTO();
            gyDeviceStatusDataDTO.setName(statusData.getDictLabel());
            gyDeviceStatusDatumDTOS.add(gyDeviceStatusDataDTO);
        }


        List<ArrayList> list1 = new ArrayList();

        for (SysDictData statusData : statusDicts) {
            ArrayList temp = new ArrayList();
            for (SysDictData type : typeDicts) {
                GyDevice device = new GyDevice();
//                if (StringUtils.isNotEmpty(locationId)) {
//                    device.setLocationId(Integer.parseInt(locationId));//根据用户所在的学院统计
//                }
                device.setDeviceType(Integer.parseInt(type.getDictValue()));
                device.setDeviceStatus(Integer.parseInt(statusData.getDictValue()));
                Integer total = deviceService.selectGyDeviceByDeviceTypeAndStatus(device);//根据设备类型，状态
                if(statusData.getDictValue().equals(DeviceStatusEnum.ERROR.getCode().toString())){
                    earlyWarnTotal+=total;
                }else if(statusData.getDictValue().equals(DeviceStatusEnum.WARNING.getCode().toString())) {
                    alarmTotal+=total;
                }else if(statusData.getDictValue().equals(DeviceStatusEnum.OFFLINE.getCode().toString())) {
                    offlineTotal+=total;
                }
                temp.add(total.toString());
            }
            list1.add(temp);
        }

        mmap.put("earlyWarnTotal",earlyWarnTotal);
        mmap.put("alarmTotal", alarmTotal);
        mmap.put("offlineTotal", offlineTotal);

        mmap.put("typeArray", typeList.toArray());  //类型组装['打磨机器人', '机械臂', '巡检机器人', '冲压机床', '数控机床']
        mmap.put("gyDeviceStatusAnalys", gyDeviceStatusDatumDTOS);
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < list1.size(); i++) {
            //构建json数组
            JSONObject stObject = new JSONObject();
            stObject.put("name", statusList.get(i));
            stObject.put("type", "bar");
            stObject.put("stack", "one");
            stObject.put("data", list1.get(i).stream().toArray());
            jsonArray.add(stObject);
        }
        mmap.put("jsonArray", jsonArray);
        SysDictData workOrderStatusDictData = new SysDictData();
        workOrderStatusDictData.setDictType("work_order_status");      // 工单状态
        List<SysDictData> workOrderStatusDicts = dictDataService.selectDictDataList(workOrderStatusDictData);
        List<NameValueDataDTO> workOrderStatusDTOS = new ArrayList<>();

        for (SysDictData typeData : workOrderStatusDicts) {
            NameValueDataDTO nameValueDataDTO = new NameValueDataDTO(typeData.getDictLabel(), "0");
            workOrderStatusDTOS.add(nameValueDataDTO);
        }

        List<NameValueDataDTO> workOrders = workOrderService.selectWorkOrderStatusTotal(new GyWorkOrder());
        for (int i=0;i<workOrderStatusDicts.size();i++) {
            for (NameValueDataDTO nameValueDataDTO : workOrders) {
                String  f =DictUtils.getDictLabel("work_order_status", workOrderStatusDicts.get(i).getDictValue());
                if (nameValueDataDTO.getName().toString().equals(f)) {
                    if(nameValueDataDTO.getName().equals(WorkOrderStatusEnum.WAIT.getInfo())){
                        waitWork +=Integer.parseInt(nameValueDataDTO.getValue());
                    }
                    workOrderStatusDTOS.get(i).setValue(nameValueDataDTO.getValue());
                }
            }
        }

       // mmap.put("waitWork", waitWork);
        mmap.put("workList", workOrderStatusDTOS.toArray());

        return "main";
    }


    // content-main class
    public String contentMainClass(Boolean footer, Boolean tagsView) {
        if (!footer && !tagsView) {
            return "tagsview-footer-hide";
        } else if (!footer) {
            return "footer-hide";
        } else if (!tagsView) {
            return "tagsview-hide";
        }
        return StringUtils.EMPTY;
    }

    // 检查初始密码是否提醒修改
    public boolean initPasswordIsModify(Date pwdUpdateDate) {
        Integer initPasswordModify = Convert.toInt(configService.selectConfigByKey("sys.account.initPasswordModify"));
        return initPasswordModify != null && initPasswordModify == 1 && pwdUpdateDate == null;
    }

    // 检查密码是否过期
    public boolean passwordIsExpiration(Date pwdUpdateDate) {
        Integer passwordValidateDays = Convert.toInt(configService.selectConfigByKey("sys.account.passwordValidateDays"));
        if (passwordValidateDays != null && passwordValidateDays > 0) {
            if (StringUtils.isNull(pwdUpdateDate)) {
                // 如果从未修改过初始密码，直接提醒过期
                return true;
            }
            Date nowDate = DateUtils.getNowDate();
            return DateUtils.differentDaysByMillisecond(nowDate, pwdUpdateDate) > passwordValidateDays;
        }
        return false;
    }
}
